﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace SugarFineUI.Framework.Uitility
{
    public class CookieHelper
    {
        public CookieHelper()
        {
        }

        /// <summary>
        /// cookies赋值
        /// </summary>
        /// <param name="strName">主键</param>
        /// <param name="strValue">键值</param>
        /// <param name="strMinutes">有效分钟数</param>
        /// <returns></returns>
        public static bool SetCookie(string strName, string strValue, int strMinutes)
        {
            try
            {
                HttpCookie cookie = new HttpCookie(strName);
                //cookie.domain = ".xxx.com";//当要跨域名访问的时候,给cookie指定域名即可,格式为.xxx.com
                cookie.Expires = DateTime.Now.AddMinutes(strMinutes);
                cookie.Value = HttpUtility.UrlEncode(strValue);
                System.Web.HttpContext.Current.Response.Cookies.Add(cookie);
                return true;
            }
            catch
            {
                return false;
            }
        }
        /// <summary>
        /// 读取cookies
        /// </summary>
        /// <param name="strname">主键</param>
        /// <returns></returns>
        public static string GetCookie(string strname)
        {
            HttpCookie cookie = System.Web.HttpContext.Current.Request.Cookies[strname];
            if (cookie != null)
            {
                if (!string.IsNullOrEmpty(cookie.Value))
                    return HttpUtility.UrlDecode(cookie.Value);
                else
                    return null;
            }
            else
            {
                return null;
            }
        }
        /// <summary>
        /// 删除cookies
        /// </summary>
        /// <param name="strname">主键</param>
        /// <returns></returns>
        public static bool DelCookie(string strname)
        {
            try
            {
                HttpCookie cookie = new HttpCookie(strname);
                //cookie.domain = ".xxx.com";//当要跨域名访问的时候,给cookie指定域名即可,格式为.xxx.com
                cookie.Expires = DateTime.Now.AddDays(-1);
                System.Web.HttpContext.Current.Response.Cookies.Add(cookie);
                return true;
            }
            catch
            {
                return false;
            }
        }
    }
}
